package com.cadre.system.service.impl;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.cadre.common.core.domain.entity.SysDictType;
import com.cadre.system.domain.officer.DIC_ZB;
import com.cadre.system.service.ISysDictTypeService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cadre.common.core.domain.entity.SysDictData;
import com.cadre.common.utils.DictUtils;
import com.cadre.system.mapper.SysDictDataMapper;
import com.cadre.system.service.ISysDictDataService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 字典 业务层处理
 * 
 * @author cadre
 */
@Service
public class SysDictDataServiceImpl implements ISysDictDataService
{
    Logger log = LoggerFactory.getLogger(SysDictDataServiceImpl.class);

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    /**
     * 根据条件分页查询字典数据
     * 
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataList(SysDictData dictData)
    {
        return dictDataMapper.selectDictDataList(dictData);
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<DIC_ZB> selectDictDataList2(String tableName)
    {
        return dictDataMapper.selectDictDataList2(tableName);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     * 
     * @param dictType 字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue)
    {
        return dictDataMapper.selectDictLabel(dictType, dictValue);
    }

    /**
     * 根据字典数据ID查询信息
     * 
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(Long dictCode)
    {
        return dictDataMapper.selectDictDataById(dictCode);
    }

    /**
     * 批量删除字典数据信息
     * 
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes)
    {
        for (Long dictCode : dictCodes)
        {
            SysDictData data = selectDictDataById(dictCode);
            dictDataMapper.deleteDictDataById(dictCode);
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
    }

    /**
     * 新增保存字典数据信息
     * 
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int insertDictData(SysDictData data)
    {
        int row = dictDataMapper.insertDictData(data);
        if (row > 0)
        {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 修改保存字典数据信息
     * 
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int updateDictData(SysDictData data)
    {
        int row = dictDataMapper.updateDictData(data);
        if (row > 0)
        {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    @Override
    public void importData() {
//        File file = new File("C:\\Users\\moyu\\Desktop\\已完成\\DIC_GB12404.xlsx");
//        ExcelReader excelReader = ExcelUtil.getReader(file, 0);
//        // 从第一行开始读
//        List<List<Object>> excel = excelReader.read(1, excelReader.getRowCount());
//
//        Long id = 22000L;
//
//        List<SysDictData> install = new ArrayList<>();
//
//        Map<String, Long> idMap = new HashMap<>();
//
//        for (List<Object> objects : excel) {
//            SysDictData sysDictData = new SysDictData();
//
//            if ("BK_ROOT".equals(objects.get(3).toString())) {
//                sysDictData.setParentDictCode("0");
//            } else {
//                sysDictData.setParentDictCode(idMap.get(objects.get(3).toString()));
//                sysDictData.setRemark(objects.get(3).toString());
//            }
//
//            sysDictData.setDictCode(id);
//            sysDictData.setDictSort(Long.valueOf(objects.get(5).toString()));
//            sysDictData.setDictLabel(objects.get(1).toString());
//            sysDictData.setDictValue(objects.get(2).toString());
//            sysDictData.setDictType("unit_membership");
//            install.add(sysDictData);
//            idMap.put(objects.get(0).toString(), id);
//            id++;
//        }
//
//        for (SysDictData sysDictData : install) {
//            if (sysDictData.getParentDictCode() == null) {
//                sysDictData.setParentDictCode(idMap.get(sysDictData.getRemark()));
//            }
//        }
//
//        for (SysDictData sysDictData : install) {
//            System.out.println(sysDictData);
//            dictDataMapper.insert(sysDictData);
//        }
    }

    @Override
    public void importDatas() {
//        File file = new File("C:\\Users\\moyu\\Desktop\\已完成\\DIC_GB10301.xlsx");
//        ExcelReader excelReader = ExcelUtil.getReader(file, 0);
//        // 从第一行开始读
//        List<List<Object>> excel = excelReader.read(1, excelReader.getRowCount());
//
//        List<SysDictData> install = new ArrayList<>();
//
//        for (List<Object> objects : excel) {
//            SysDictData sysDictData = new SysDictData();
//
//            if ("BK_ROOT".equals(objects.get(3).toString())) {
//                sysDictData.setParentDictCode(0L);
//            }
//            sysDictData.setDictSort(Long.valueOf(objects.get(5).toString()));
//            sysDictData.setDictLabel(objects.get(1).toString());
//            sysDictData.setDictValue(objects.get(2).toString());
//            sysDictData.setDictType("purpose_of_going_abroad");
//            install.add(sysDictData);
//        }
//
//        for (SysDictData sysDictData : install) {
//            System.out.println(sysDictData);
//            dictDataMapper.insert(sysDictData);
//        }
    }

    /**
     * 批量导入字典
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDatasBatch() throws IOException {

        Long initAutoId = 1000000L;
        // 读取汇总表
        String prefix = "C:\\Users\\yangz\\Desktop\\test\\";
        String summaryCsvPath = prefix + "DIC_GB_MANAGE.csv";
        try (Reader reader = new FileReader(summaryCsvPath);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader())) {

            for (CSVRecord csvRecord : csvParser) {

                String code = "";

                try {
                    /**
                     * 原始数据的id映射关系
                     *
                     * key-旧数据id
                     * value-新数据id
                     */
                    Map<String, Long> idMap = new HashMap<>();

                    // 按列名访问数据 (如果 CSV 文件有标题行)
                    code = csvRecord.get("TABLECODE");
                    String name = csvRecord.get("TABLENAME");
                    String desc = csvRecord.get("TABLEDESC");

                    // 先查询是否存在type？
                    SysDictType dictTypeDb = sysDictTypeService.selectDictTypeByType(code);
                    if (dictTypeDb == null) {
                        // 插入字典
                        SysDictType dictType = new SysDictType();
                        dictType.setDictName(name);
                        dictType.setDictType(code);
                        dictType.setRemark(desc);
                        dictType.setStatus("0");
                        sysDictTypeService.insertDictType(dictType);
                    }

                    // 查询字典对应的值
                    Reader dictDataReader = new FileReader(prefix + code.toUpperCase() + ".csv");
                    CSVParser dictDataParser = new CSVParser(dictDataReader, CSVFormat.DEFAULT.withHeader());
                    for (CSVRecord dataRecord : dictDataParser) {
                        // 按列名访问数据 (如果 CSV 文件有标题行)
                        String dataCode = dataRecord.get("CODE");
                        String dataName = dataRecord.get("NAME");
                        String dataParent = "BK_ROOT".equals(dataRecord.get("FCODE")) ? "0" : dataRecord.get("FCODE");
                        String dataDesc = dataRecord.get("TDESC");

                        SysDictData dictData = new SysDictData();
                        dictData.setDictSort(0L);
                        dictData.setDictType(code);
                        dictData.setDictLabel(dataName);
                        dictData.setDictValue(dataName);
                        dictData.setListClass("primary");
                        dictData.setStatus("0");
                        dictData.setDictCode(initAutoId);
                        if (StringUtils.isNotEmpty(dataParent)) {
                            try {
                                dictData.setParentDictCode(dataParent);
                            } catch (Exception ex) {
                                log.error("格式化LONG异常，默认0L");
                                dictData.setParentDictCode("0");
                            }
                        } else {
                            dictData.setParentDictCode("0");
                        }
                        dictDataMapper.insertDictData(dictData);

                        try {
                            String key = Integer.valueOf(dataCode).toString();
                            idMap.put(key, dictData.getDictCode());
                        }catch (Exception ex) {
                            idMap.put(dataCode, dictData.getDictCode());
                            log.error("格式化Integer出错");
                        }

                        initAutoId++;
                    }

                    // 查询所有当前类型的字典值，然后替换父code
                    List<SysDictData> dictDataList = dictDataMapper.selectListByDictType(code);
                    for (SysDictData dictData : dictDataList) {
                        String oldParentCode = dictData.getParentDictCode();
                        if (oldParentCode != null) {
                            Long newParentCode = idMap.get(oldParentCode.toString());
                            dictData.setParentDictCode(newParentCode.toString());
                            dictDataMapper.updateDictData(dictData);
                        }
                    }

                    log.info("字典导入成功：{}" , code);
                } catch (Exception ex) {
                    log.error("字典导入发生异常！" + code);
                    ex.printStackTrace();
                }

            }
        }

    }
}
